package com.sense.kukoo.common.mvvm.view

import android.annotation.SuppressLint
import android.os.Build
import android.os.Bundle
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import androidx.databinding.DataBindingUtil
import androidx.databinding.ViewDataBinding
import androidx.lifecycle.LifecycleOwner
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModelProvider
import com.gyf.immersionbar.ImmersionBar
import com.sense.kukoo.common.mvvm.vm.BaseViewModel
import com.sense.kukoo.common.R
import com.sense.kukoo.common.wiget.dialog.LoadDialog
import com.sense.kukoo.lib_logger.LoggerManager
import com.zy.multistatepage.MultiStateContainer
import com.zy.multistatepage.bindMultiState


/**
@Author Lionszhang
@Date   2021/2/25 16:36
@Name   BaseActivity.kt
@Instruction MVVM层Activity基类，所有Activity子界面应当继承
 */
abstract class BaseMvvmActivity<V : BaseViewModel, B : ViewDataBinding> : AppCompatActivity(),
    IView {
    var mSavedInstanceState: Bundle? = null
    lateinit var mBinding: B
    lateinit var mViewModel: V
    private var loadingProgressDialog: LoadDialog? = null
    protected lateinit var multiState: MultiStateContainer
    private var TAG: String? = "BaseActivity"

    @SuppressLint("MissingSuperCall")
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        mSavedInstanceState = savedInstanceState
        mBinding = DataBindingUtil.setContentView(this, getLayoutId())
        multiState = mBinding.root.bindMultiState()
        mViewModel = createViewModel(getViewModelClass())
        initStatusBar()
        initBaseData()
        initData()
        initView()
    }

    /**
    @Author  Lionszhang
    @Date   2021/2/24 15:06
    @Return  返回Activity对应的ViewModel
     */
    private fun createViewModel(clazz: Class<V>): V {
        return ViewModelProvider(this).get(clazz)
    }

    /**
    @Author  Lionszhang
    @Date   2021/3/9 16:31
    @Param  Activity有无Fragment
    @Instruction 默认Activity无Fragment  如果是Activity有Fragment 子类重写设置为 ture 避免Fragment和Activity重复注册观察者重复响应
     */
    private fun initBaseData() {
        mViewModel.mHintInfoLiveData.observe(this) {
            LoggerManager.e("mHintInfoLiveData=${it}")
            Toast.makeText(this, it, Toast.LENGTH_SHORT).show()
        }
        /**VM层与V层交互默认处理方式*/
        mViewModel.mNavLiveDate.observe(this) {
            when (it) {
                BaseViewModel.ACTION_SHOW_DIALOG -> {
                    showLoadingDialog()
                }
                BaseViewModel.ACTION_HIDE_DIALOG -> {
                    hideLoadingDialog()
                }
                else -> {
                    responseVM(it)
                }
            }
        }

        mViewModel.mShowNetworkError.observe(this) { networkError ->
            networkError?.let {
                mViewModel.mShowNetworkError.value = null
                onShowNetworkError()
            }
        }
    }

    //默认的网络错误实现
    open fun onShowNetworkError() {}

    /**
    @Author  Lionszhang
    @Date   2021/3/8 16:09
    @Param action 动作常量
    @Instruction  对VM层的默认响应函数
     */
    abstract override fun responseVM(action: Int)

    /**
     * 初始化状态栏
     */
    open fun initStatusBar() {
        ImmersionBar.with(this)
            .barColor(com.sense.kukoo.lib_multistatepage.R.color.white)
            .statusBarDarkFont(true)
            .navigationBarDarkIcon(true)
            .fitsSystemWindows(true)
            .init()
    }

    /**
     * 获取activity布局id
     */
    abstract fun getLayoutId(): Int

    /**
     * 获取ViewModel的class
     */
    abstract fun getViewModelClass(): Class<V>


    /**
     * 获取状态栏颜色
     */
    open fun getStatusBarColor(): Int {
        return R.color.colorPrimary
    }

    protected fun showLoadingDialog() {
        if (!isDestroyed && !isFinishing) {
            getLoadingProgressDialog()?.show()
        }
    }

    private fun getLoadingProgressDialog(): LoadDialog? {
        if (!isDestroyed && !isFinishing) {
            if (loadingProgressDialog == null) {
                loadingProgressDialog = LoadDialog(this)
            }
        }
        return loadingProgressDialog
    }

    protected fun hideLoadingDialog() {
        if (!isDestroyed && loadingProgressDialog?.isShowing == true) {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                loadingProgressDialog?.dismiss()
            } else {
                loadingProgressDialog?.hide()
            }
        }
    }

    protected fun <T> bindAction(
        data: MutableLiveData<T>,
        owner: LifecycleOwner,
        action: (t: T) -> Unit
    ) {
        data.observe(owner) {
            it?.let {
                data.value = null
                action(it)
            }
        }
    }

    protected fun <T> bindAction(data: MutableLiveData<T>, action: (t: T) -> Unit) {
        bindAction(data, this, action)
    }

    protected fun <T> bindData(
        data: MutableLiveData<T>,
        owner: LifecycleOwner,
        action: (t: T) -> Unit
    ) {
        data.observe(owner, action)
    }

    protected fun <T> bindData(data: MutableLiveData<T>, action: (t: T) -> Unit) {
        data.observe(this, action)
    }
}